import type { TemplateSchemaItem } from '@/services/develop/types';
import {
  addTemplateSchema,
  updateTemplateSchema,
  removeTemplateSchema,
} from '@/services/develop/templateSchema';
import { message } from 'antd';

/**
 * 添加模板方案
 *
 * @param fields
 */
export const handleAdd = async (fields: TemplateSchemaItem) => {
  const hide = message.loading('正在新增模板方案');

  try {
    await addTemplateSchema({ ...fields });
    hide();
    message.success('模板方案添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('模板方案添加失败，请重试！');
    return false;
  }
};

/**
 * 更新模板方案
 *
 * @param fields
 */
export const handleUpdate = async (fields: TemplateSchemaItem, currentRow?: TemplateSchemaItem) => {
  const hide = message.loading('正在更新模板方案');

  try {
    await updateTemplateSchema({
      ...currentRow,
      ...fields,
    });
    hide();
    message.success('模板方案更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('模板方案更新失败，请重试');
    return false;
  }
};

/**
 * 删除模板方案
 *
 * @param selectedRows
 */
export const handleRemove = async (selectedRows: TemplateSchemaItem[]) => {
  const hide = message.loading('正在删除模板方案');
  if (!selectedRows) return true;

  try {
    await removeTemplateSchema(selectedRows.map((row) => row.id));
    hide();
    message.success('模板方案删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('模板方案删除失败，请重试');
    return false;
  }
};
